<template>
<q-page class="column items-center bg-grey-1 ">
    <q-card flat class="column  transparent  flex-center q-mt-xs">
        <q-card-section class="q-py-none">
            <q-img src="~assets/icons/一方映画logo20191201版（透明版）.png" spinner-color="white" class="logo-img" contain />
        </q-card-section>
        <q-card-section class="column flex-center text-grey-6 text-caption q-py-none">
            <div> <span>/</span> 致力于高品质视听文化创意传播 <span>/</span></div>
            <div></div>

        </q-card-section>
        <q-card-section class="column flex-center">
            <div class="row q-gutter-md">
                <div class="row flex-center text-grey-6 text-suntitle1 ">
                    <q-icon name="mdi-calendar-check-outline " class="q-mr-sm"></q-icon> 一站项目跟踪
                </div>
                <div class="row flex-center text-grey-6 text-suntitle1 ">
                    <q-icon name="mdi-account-group-outline " class="q-mr-sm"></q-icon> 多人项目协作
                </div>

            </div>
            <div class="row q-gutter-md">
                <div class="row flex-center text-grey-6 text-suntitle1 ">
                    <q-icon name="mdi-movie-edit-outline " class="q-mr-sm"></q-icon> 媒体播放审阅
                </div>
                <div class="row flex-center text-grey-6 text-suntitle1 ">
                    <q-icon name="mdi-shield-lock-outline " class="q-mr-sm"></q-icon> 数据安全加密
                </div>

            </div>
        </q-card-section>
    </q-card>

    <q-card v-if="isPhotoShow" flat class="row flex-center q-py-md transparent col-grow">
        <q-icon size="300px">
            <q-img src="~assets/icons/loginindex.svg"></q-img>
        </q-icon>
    </q-card>

    <q-card flat class="col-grow column flex-center transparent">
        <div v-if="isWechatQrLogin" class="q-pt-none column flex-center q-pa-md">
            <div class="row q-my-md">
                <div style="width: 30px; height: 30px">
                    <img style="width: 100%; height: 100%" src="~assets/icons/wechat.png" />
                </div>
                <div class="text-primary q-ml-sm text-h5">微信登录</div>
            </div>

            <div ref="qrCodediv"></div>
            <div class="q-mt-md text-grey">请用使用手机微信扫码登录</div>
        </div>

        <div v-if="isAccountLogin">
            <q-form @submit="onAccountSubmit" class="q-gutter-md" style="width: 250px">
                <q-input rounded outlined v-model="name" label="手机号" lazy-rules :rules="[(val) => (val && val.length > 0 && /^1[3-9]\d{9}$/.test(val)) || '请输入正确的手机号']" />

                <q-input rounded outlined type="password" v-model="password" label="密码" lazy-rules :rules="[(val) => (val !== null && val !== '') || '请输入密码']" />
                <div style="display: flex; justify-content: center">
                    <q-btn style="width: 100px" outline label="登录" type="submit" color="primary" />
                </div>
            </q-form>
        </div>
        <div v-if="isPhoneLogin" class="row flex-center">
            <q-form @submit="onPhoneSubmit" class="q-gutter-md" style="width: 250px">
                <q-input rounded outlined placeholder="请输入手机号" v-model="name" label="手机号" lazy-rules :rules="[(val) => (val && val.length > 0 && /^1[3-9]\d{9}$/.test(val)) || '请输入正确的手机号']" />

                <q-input rounded outlined placeholder="请输入验证码" v-model="code" label="验证码" lazy-rules :rules="[(val) => (val !== null && val !== '') || '请输入验证码']">
                    <template v-slot:append v-if="isPhoneLogin">
                        <q-btn @click="sendPhoneCode" dense flat push class="text-primary" :disable="isSend" icon="send" :label="isSend?codeMsg:'发送'"></q-btn>
                    </template>
                </q-input>
                <div style="display: flex; justify-content: center">
                    <q-btn style="width: 100px" outline label="登录" type="submit" color="primary" />
                </div>
            </q-form>
        </div>

    </q-card>
    <div v-if="isQwQrLogin" class="q-pt-none column items-center q-pa-md">

        <div class="no-scroll" id="QwQrDiv"></div>

    </div>
    <q-card flat class="col-auto column flex-center transparent">
        <q-checkbox keep-color v-model="isRemember" label="15天内记住我" color="teal" />
    </q-card>
    <q-card v-if="!isInBrower" flat style="height:180px" class="flex-center transparent">
        <q-card-section class="q-pb-sm" v-if="isQwFastLogin">
            <q-btn stretch outline color="primary" class="q-px-sm q-py-xs full-width">
                <a :href="qwFastLoginUrl" style="text-decoration: none;width:100%" class="row flex-center text-teal-5" target="" rel="noopener noreferrer">

                    <q-avatar style="width: 25px; height: 22px" class="q-mr-sm">
                        <img src="~assets/icons/qwlogo.png" />
                    </q-avatar>
                    <div class="text-subtitle1">快速登录</div>
                </a>

            </q-btn>

        </q-card-section>
        <q-card-section class="q-pb-sm" v-if="isWechatFastLogin">

            <q-btn stretch outline color="primary" class="q-px-sm q-py-xs full-width">
                <a :href="wechatloginsrc" style="text-decoration: none;width:100%" class="row flex-center text-teal-5" target="" rel="noopener noreferrer">

                    <q-avatar size="25px" class="q-mr-sm">
                        <img src="~assets/icons/wechat.png" />
                    </q-avatar>
                    <div class="text-subtitle1">快速登录</div>
                </a>

            </q-btn>

        </q-card-section>

        <q-card-section class="q-pt-sm q-gutter-sm">
            <q-btn outline color="teal-3" :disable="isPhoneLogin" icon="mdi-cellphone" @click="handlePhoneLogin">
                <div class=" text-subtitle1">验证码登录</div>
            </q-btn>
            <q-btn outline color="teal-3" :disable="isAccountLogin" icon="mdi-lock-outline" @click="handleAccountLogin">
                <div class=" text-subtitle1">密码登录</div>
            </q-btn>
        </q-card-section>

    </q-card>
    <q-card v-if="isInBrower" flat style="height:180px;max-width:900px" class="flex-center q-pt-lg transparent ">

        <q-card-section class="q-pb-sm ">

            <q-btn stretch outline :disable="isPhoneLogin" @click="handlePhoneLogin" color="primary" icon="mdi-cellphone" class="q-px-sm q-py-xs full-width">
                <div class="text-subtitle1">验证码登录</div>

            </q-btn>

        </q-card-section>
        <q-card-section class="row no-wrap q-pt-sm q-gutter-sm q-pb-sm">
            <q-btn outline :disable="isQwQrLogin" color="teal-3" @click="handleQwQrLogin">

                <q-avatar style="width: 25px; height: 22px" class="q-mr-sm">
                    <img src="~assets/icons/qwlogo.png" />
                </q-avatar>
                <div class="text-subtitle1">扫码登录</div>
            </q-btn>
            <q-btn outline :disable="isWechatQrLogin" color="teal-3" @click="handleWechatQrLogin">
                <q-avatar size="25px" class="q-mr-sm">
                    <img src="~assets/icons/wechat.png" />
                </q-avatar>
                <div class="text-subtitle1">扫码登录</div>
            </q-btn>
            <q-btn outline :disable="isAccountLogin" color="teal-3" @click="handleAccountLogin">
                <q-icon name="mdi-lock-outline"></q-icon>
                <div class=" text-subtitle1">密码登录</div>
            </q-btn>
        </q-card-section>

    </q-card>

</q-page>
</template>

<script>
import request from "assets/utils/request";
import {

    confirmlogin,
} from "assets/api/studio";
import {
    setItem
} from "assets/utils/storage";
import md5 from "js-md5";
import {
    setTimeout
} from "timers";
import QRCode from "qrcodejs2";

export default {
    name: "LoginIndexPage",
    data() {
        return {
            isQw: false,
            isWechat: false,
            name: null,
            password: null,
            code: null,
            loginsrc: "",
            isQwQrLogin: false,
            qwFastLoginUrl: "",
            wechatloginsrc: "",

            i: {},
            isPhoneLogin: true,
            isAccountLogin: false,
            isWechatFastLogin: false,
            isWechatQrLogin: false,
            isQwFastLogin: false,
            isPhotoShow: false,
            isInBrower: true,
            isSend: false,
            wwLogin: '',
            codeMsg: '',
            isRemember: false,

        };
    },
    created() {

    },
    mounted() {

        if (this.$platform.inWechat()) {
            this.isAccountLogin = false;
            this.isWechatFastLogin = true;
            this.isPhotoShow = true;
            this.isInBrower = false;
            this.isPhoneLogin = false;
            this.handleWechatFastLogin();
        };
        if (this.$platform.inQw()) {
            this.isInBrower = false;
            this.isAccountLogin = false;
            this.isPhotoShow = true;
            this.isQwFastLogin = true;
            this.isPhoneLogin = false;
            this.handleQwFastLogin();
        };

        // //微信小程序中登录
        // if (window.__wxjs_environment === "miniprogram") {
        //     this.isWechat = true;
        //     let appid = "wx19f35b368b121f53";
        //     let url = this.$route.query.redirect;
        //     if (url) {
        //         var redirecturl = encodeURIComponent(
        //             "https://oa.yfyh.cc" + url + "&platform=wechat&"
        //         );
        //     } else {
        //         var redirecturl = encodeURIComponent("https://oa.yfyh.cc?platform=wechat&");
        //     }

        //     this.wechatloginsrc =
        //         "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
        //         appid +
        //         "&redirect_uri=" +
        //         redirecturl +
        //         "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        // }

        // this.handleQwFastLogin();
    },
    methods: {
        handleLoginWayChange(tabname) {
            if (!this.isInBrower) {
                this.isPhotoShow = false;
            }

            let tabName = ['isPhoneLogin', 'isAccountLogin', 'isQwQrLogin', 'isWechatQrLogin'];

            tabName.forEach(item => {
                if (tabname == item) {
                    this[`${item}`] = true;
                } else {
                    this[`${item}`] = false;
                }

            })
            if (tabname != 'isWechatQrLogin' && JSON.stringify(this.i) != "{}") {
                this.cancelWechatQrLogin();
            }

        },

        handleWechatFastLogin() {
            let appid = "wx19f35b368b121f53";
            let url = this.$route.query.redirect;

            if (url) {

                if (url.indexOf('?') != -1 || url.indexOf('%3F') != -1) {

                    var redirecturl = encodeURIComponent(
                        "https://oa.yfyh.cc" + url + "&platform=wechat&"
                    );
                } else {

                    var redirecturl = encodeURIComponent(
                        "https://oa.yfyh.cc" + url + "?platform=wechat&"
                    );
                }

            } else {
                var redirecturl = encodeURIComponent("https://oa.yfyh.cc?platform=wechat&");
            }
            this.isAccountLogin = false;
            this.wechatloginsrc =
                "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                appid +
                "&redirect_uri=" +
                redirecturl +
                "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        },
        randomCoding() {
            //创建26个字母数组
            var arr = [
                "A",
                "B",
                "C",
                "D",
                "E",
                "F",
                "G",
                "H",
                "I",
                "J",
                "K",
                "L",
                "M",
                "N",
                "O",
                "P",
                "Q",
                "R",
                "S",
                "T",
                "U",
                "V",
                "W",
                "X",
                "Y",
                "Z",
            ];
            var idvalue = "";
            var n = 4; //这个值可以改变的，对应的生成多少个字母，根据自己需求所改
            for (var i = 0; i < n; i++) {
                idvalue += arr[Math.floor(Math.random() * 26)];
            }
            return idvalue;
        },
        cancelWechatQrLogin() {
            clearInterval(this.i);
            this.i = {};
        },

        async handleWechatQrLogin() {
            this.handleLoginWayChange('isWechatQrLogin');
            let appid = "wx19f35b368b121f53";
            let zimu = await this.randomCoding();
            let state = new Date().getTime() + zimu;
            let redirecturl = encodeURIComponent("http://oa.yfyh.cc/codepage");
            let loginsrc =
                "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                appid +
                "&redirect_uri=" +
                redirecturl +
                "&response_type=code&scope=snsapi_userinfo&state=" +
                state +
                "#wechat_redirect";
            new QRCode(this.$refs.qrCodediv, {
                text: loginsrc,
                width: 150,
                height: 150,
                colorDark: "#333333", //二维码颜色
                colorLight: "#ffffff", //二维码背景色
                correctLevel: QRCode.CorrectLevel.L, //容错率，L/M/H
            });
            let reqdata = {
                state: state,
            };
            var total = 0;

            var vm = this;
            this.i = setInterval(() => {
                total++;
                if (total == 50) {
                    vm.$q.notify({
                        color: "red-5",
                        textColor: "white",
                        icon: "warning",
                        position: "top",
                        message: "请求超时，请重新扫码！",
                        timeout: 1000,
                    });

                    clearInterval(vm.i);
                }
                confirmlogin(reqdata).then((res) => {
                    if (res.data.code == 1) {
                        let user = {
                            token: res.data.token
                        };
                        let userinfo = res.data.data;
                        console.log(user, userinfo);
                        this.$storage.setItem('user', user);
                        this.$storage.setItem('userinfo', userinfo);

                        vm.user = res.data.data[0];
                        vm.$q.notify({
                            position: "top",
                            message: "登录成功！",
                            timeout: 1000,
                            color: "light-green-4",
                            icon: "far fa-check-circle",
                            textColor: "white",
                        });
                        clearInterval(vm.i);
                        let url = this.$route.query.redirect;
                        if (url) {
                            vm.$router.push({
                                path: decodeURIComponent(url),
                            });
                        } else {
                            vm.$router.push("/");
                        }

                    }
                });
            }, 2000);

        },
        isWxBrowser() {
            var ua = navigator.userAgent.toLowerCase();
            let isWxWork = ua.match(/WxWork/i) == "wxwork";
            if (isWxWork) {
                return true;
            } else {
                return false;
            }
        },
        handleQwQrLogin() {
            this.handleLoginWayChange('isQwQrLogin');
            let appid = "wwc7ba5e38ee27ab0f";
            // 取到原页面路径
            let url = this.$route.query.redirect;
            if (url) {
                var redirecturl = encodeURIComponent("http://oa.yfyh.cc" + url + "&platform=qw&");
            } else {
                var redirecturl = encodeURIComponent("http://oa.yfyh.cc/?platform=qw&");
            }
            let agentid = 1000038;
            // let loginUrl = `https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=${appid }&agentid=${agentid}&redirect_uri=${redirecturl}&state=STATE`

            setTimeout(() => {
                new WwLogin({
                    "id": 'QwQrDiv',
                    "appid": appid,
                    "agentid": agentid,
                    "redirect_uri": redirecturl,
                    "state": "",
                    "href": "https://api.yfyh.cc/data/qwLogin.css"

                });

            }, 200)

        },
        handleQwFastLogin() {
            let appid = "wwc7ba5e38ee27ab0f";
            let agentid = 1000038;
            // 取到原页面路径
            let url = this.$route.query.redirect;
            if (url) {

                if (url.indexOf('?') != -1 || url.indexOf('%3F') != -1) {

                    var redirecturl = encodeURIComponent(
                        "https://oa.yfyh.cc" + url + "&platform=qw&"
                    );
                } else {

                    var redirecturl = encodeURIComponent(
                        "https://oa.yfyh.cc" + url + "?platform=qw&"
                    );
                }
            } else {
                var redirecturl = encodeURIComponent("http://oa.yfyh.cc/?platform=qw&");
            }
            this.qwFastLoginUrl = ` https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirecturl}&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=${agentid}#wechat_redirect`

        },
        handleAccountLogin() {
            this.handleLoginWayChange('isAccountLogin')
        },
        handlePhoneLogin() {
            this.handleLoginWayChange('isPhoneLogin')
        },
        onAccountSubmit() {
            let vm = this;
            // 取到原页面路径
            let url = this.$route.query.redirect;

            request
                .post("oa/login", {
                    phonenum: this.name,
                    password: md5(md5(this.password)),
                    isRemember: this.isRemember
                })
                .then((res) => {
                    if (res.data.code == 1) {

                        let user = {
                            token: res.data.token
                        };
                        let userinfo = res.data.data;

                        this.$storage.setItem('user', user);
                        this.$storage.setItem('userinfo', userinfo);
                        vm.$q.notify({
                            color: "light-green-4",
                            icon: "far fa-check-circle",
                            position: "top",
                            textColor: "white",
                            message: "登陆成功！",
                            timeout: "1500",
                        });

                        setTimeout(() => {
                            if (url) {
                                vm.$router.push({
                                    path: decodeURIComponent(url),
                                });
                            } else {
                                vm.$router.push("/");
                            }

                        }, 500);

                    } else {
                        vm.$q.notify({
                            color: "red-5",
                            textColor: "white",
                            icon: "warning",
                            position: "top",
                            message: "登陆失败，用户名或密码错误！",
                        });
                    }
                })
                .catch((err) => {
                    vm.$q.notify({
                        color: "red-5",
                        textColor: "white",
                        icon: "warning",
                        position: "top",
                        message: "登陆失败，用户名或密码错误！",
                    });
                });
        },
        onPhoneSubmit() {
            var vm = this;
            let url = this.$route.query.redirect;
            if (this.userStatus == 3) {
                let appid = "wx19f35b368b121f53";
                let url = this.$route.query.redirect;
                if (url) {
                    var redirecturl = encodeURIComponent(
                        "https://oa.yfyh.cc" + url + "?phonenum=" + this.name + "&phonecode=" + this.code
                    );
                } else {
                    var redirecturl = encodeURIComponent("https://oa.yfyh.cc?phonenum=" + this.name + "&phonecode=" + this.code);
                }
                let openurl =
                    "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                    appid +
                    "&redirect_uri=" +
                    redirecturl +
                    "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                window.open(openurl, '_self')
            } else {
                request
                    .post("oa/phonelogincheck", {
                        phonenum: this.name,
                        code: this.code,
                        status: this.userStatus,
                        isRemember: this.isRemember
                    })
                    .then((res) => {
                        if (res.data.code == 1) {

                            let user = {
                                token: res.data.token
                            };
                            let userinfo = res.data.data;

                            this.$storage.setItem('user', user);
                            this.$storage.setItem('userinfo', userinfo);
                            vm.$q.notify({
                                color: "light-green-4",
                                icon: "far fa-check-circle",
                                position: "top",
                                textColor: "white",
                                message: "登陆成功！",
                                timeout: "1500",
                            });

                            setTimeout(() => {
                                if (url) {
                                    vm.$router.push({
                                        path: decodeURIComponent(url),
                                    });
                                } else {
                                    vm.$router.push("/");
                                }

                            }, 500);

                        } else {
                            vm.$q.notify({
                                color: "red-5",
                                textColor: "white",
                                icon: "warning",
                                position: "top",
                                message: "登陆失败，用户名或密码错误！",
                            });
                        }
                    })
                    .catch((err) => {
                        vm.$q.notify({
                            color: "red-5",
                            textColor: "white",
                            icon: "warning",
                            position: "top",
                            message: "登陆失败，用户名或密码错误！",
                        });
                    });

            };

        },
        sendPhoneCode() {
            var vm = this;
            if (/^1[3-9]\d{9}$/.test(this.name)) {
                this.isSend = true;
                var time = 60;
                request
                    .post("oa/sendcode", {
                        phonenum: this.name,
                    })
                    .then((res) => {
                        if (res.data.code == 1) {
                            console.log('用户判断', res.data.status);
                            this.userStatus = res.data.status;

                            vm.$q.notify({
                                color: "light-green-4",
                                icon: "far fa-check-circle",
                                position: "top",
                                textColor: "white",
                                message: "发送成功！",
                                timeout: "1500",
                            });

                        } else {
                            vm.$q.notify({
                                color: "red-5",
                                textColor: "white",
                                icon: "warning",
                                position: "top",
                                message: "发送失败",
                            });
                        }
                    })
                    .catch((err) => {
                        vm.$q.notify({
                            color: "red-5",
                            textColor: "white",
                            icon: "warning",
                            position: "top",
                            message: "发送失败!",
                        });
                    });

                var i = setInterval(() => {
                    time--;

                    this.codeMsg = time + "s";
                    if (time == 0) {
                        clearInterval(i);
                        this.isSend = false;
                        this.codeMsg = "发送";
                    }
                }, 1000);
            }

        },
    },
};
</script>

<style scoped>
.logo-img {
    height: 150px;
    width: 150px;
}

iframe {
    width: 200px;
    height: 200px;
}
</style>
